<template>
	<view>

		<st-mc-framework navTitle="古越电源注塑MES" @changeLevel="changeLevel">

			<template #content>
				<view class="contentBox">
					<u-row class="u-row_view">
						<u-col span="8">
							<view class="demo-layout bg-purple-light u-row_view_left">
								<text>管理部 现场 质管员巡查日报 </text>
								<text> 检查时间：{{CheckTime}}</text>
							</view>
						</u-col>
						<u-col span="4">
							<view class="demo-layout bg-purple  u-row_view_right">
								<text>Q/GY-QP034-05</text> <button size="mini" @click='addtable'>新增</button>
							</view>

						</u-col>
					</u-row>
					<view class="table">

						<table style="table-layout: fixed;">
							<tr>
								<th width='6%'>操作</th>
								<th width='5%'>序号</th>
								<th width='8%'>质管员</th>
								<th width='8%'>巡检车间</th>
								<th width='14%'>现场情况描述</th>
								<th width='14%'>现场照片</th>
								<th>要求</th>
								<th width='8%'>整改责任人</th>
								<th width='8%'>部门监督人</th>
								<th width='8%'>完成期限</th>
								<th>改进对策</th>
								<th>备注次数</th>
							</tr>
							<tbody>

								<tr v-for="(item,index) in contents">
									<td @click="trash(index)">
										<view class="trashView">
											<u-icon name="trash" size="30"></u-icon>
										</view>
									</td>
									<td>{{index+1}}</td>
									<td>{{item.QCName}}</td>
									<td @click='openBaseScreen("日报车间",index)'>{{item.FWorkShopName}}</td>
									<td><input type="text" v-model="item.Situation" @input="addinput" /></td>
									<td style="text-align: center;">
										<u-upload style=" width: 50%;margin: auto;" :fileList="item.DImgs"
											@afterRead="afterRead($event,index)" @delete="deletePic($event,index)"
											multiple :maxCount="1" :previewFullImage="true"></u-upload>
									</td>
									<td>
										<uni-data-checkbox multiple v-model="item.Require" :localdata="sexs" />
									</td>
									<td @click='openBaseScreen("日报责任人",index)'>{{item.ResponseMan}}</td>
									<td @click='openBaseScreen("日报监督人",index)'>{{item.Supervisor}}</td>
									<td @click="addTime(index)">{{item.DeadLine}}</td>

									<td><input type="text" v-model="item.Improvements" @input='addinput' /></td>
									<td><input type="text" v-model="item.FRemarks" @input='addinput' /></td>
								</tr>
							</tbody>
						</table>

						<table style="table-layout: fixed;">
							<tr>
								<th width='11%' @click="addChildList">
									<view>姓名 <u-icon class="u_icon" name="plus"></u-icon></view>
								</th>
								<th v-for="(item,index) in ChildsList" :key="index">
									<view>
										<u-icon style="float: left;" name="minus" @click='deleteScreen(index)'></u-icon>
										{{item.XJMan}}
										<u-icon class="u_icon" name="arrow-down"
											@click='openBaseScreen("质管员",index)'></u-icon>
									</view>
								</th>
								<th width='34%'>备注</th>
							</tr>
							<tbody>
								<tr>
									<td>巡检情况</td>
									<td v-for="(item,index) in ChildsList" :key="index">
										<input type="text" v-model="item.XJSituation" />
									</td>
									<td rowspan='2'> <input type="text" v-model="ChildList.FRemarksZ" /></td>
								</tr>
								<tr>
									<td>问题件数</td>
									<td v-for="(item,index) in ChildsList" :key="index">
										<input type="text" v-model="item.XJNGNum" />
									</td>

								</tr>
							</tbody>
						</table>

					</view>
					<view class="DetailsbottomBtnsTow">
						<button class="button1" block @click="submit('保存')">
							保存
						</button>
						<button v-if='ApproveBack("审核")' class="button2" block @click="toexamine" v-show="buttonShow">
							审核
						</button>

					</view>
				</view>

				<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show = false' @close="show=false"
					@confirm='pickerConfirm'></u-datetime-picker>
				<u-toast ref="uToast"></u-toast>

				<u-popup :show="popup_logout" mode="center" :closeOnClickOverlay="false" :round="4">
					<view class="popup-content">
						<view class="popup-content_close x-c">
							<uni-icons type="closeempty" color="#999" size="20"
								@click='popup_logout = false'></uni-icons>
						</view>
						<view class="x-c title">
							<text>{{popuptitle}}</text>
						</view>
						<view class="contentView">
							<text>{{popupcontent}}</text>
						</view>
						<view class="btnBox x-ac">
							<u-button v-show="popuptitle=='审核'" type="info" text="取消"
								@click='popup_logout=false'></u-button>
							<u-button type="primary" text="确定" @click="confirmClick"></u-button>
						</view>
					</view>
				</u-popup>
			</template>
		</st-mc-framework>
		<u-loading-page :loading="loadingPage" class="loading-page" loading-text="正在保存中"></u-loading-page>
	</view>
</template>
<script>
	import {
		LogLevel
	} from '../../uni_modules/Lyuan-SignalR/js_sdk/signalr';
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';
	
	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				popupName: '',
				popuptitle: '',
				popupcontent: '',
				popup_logout: false,
				buttonShow: false,
				contentIndex: null,
				TimeIndex: null,
				ChildListIndex: 1,
				loadingPage: false,
				comentIndex: null,
				serverIP: '',
				CheckTime: '',
				show: false,
				value1: Number(new Date()),
				contents: [{
					CkPatrolDailyDeID: 0,
					time: '',
					Result: '',
					PicPath: '',
					DeadLine: '',
					Supervisor: '',
					Improvements: '',
					ResponseMan: '',
					Require: ['整改', '考核'],
					Situation: '',
					FWorkShopName: '17号车间',
					FWorkShopID: '1011',
					CheckTime: '',
					QCName: '',
					FRemarks: '',
					DImgs: [],
				}],
				ChildsList: [{
					XJMan: '',
					XJNGNum: '',
					XJSituation: ''
				}],

				// 子表备注
				ChildList: {
					CkPatrolDailyID: 0,
					FRemarksZ: '',
				},
				sexs: [{
					text: '整改',
					value: '整改'
				}, {
					text: '评估',
					value: '评估'
				}, {
					text: '考核',
					value: '考核'
				}],
				BtnApprove: []
			};
		},
		onLoad(onlod) {
			let that = this;

			let foundNode = null;
			for (const module of this.$store.state.appConfigInfo.ModuleInfo_All) {
				if (module.TreeTypeName === '生产检验') {
					for (const node of module.Node) {
						if (node.APFunName === '巡查日报') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}
			that.BtnApprove = foundNode['IconApprove'];

			console.log(onlod);
			that.$store.state.GuyueModule.MesBasicInfo.Status.ClockStatusTitle = '其他'
			if (onlod.CkPatrolDailyID) {
				that.queryList(onlod.CkPatrolDailyID)
			} else {
				that.CheckTime = getFormatDate()
				that.contents[0].DeadLine = getFormatDateTime(new Date())
				that.contents[0].QCName = that.$store.state.UserInfo.EmplName
				console.log(this.$store.state.UserInfo);
			}


		},
		onShow() {
			this.getValue
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}
				return Type;
			},
			confirmClick() {
				var that = this
				that.popup_logout = false
				if (that.popupName == '主表') {
					that.ChildsList.splice(that.contentIndex, 1);
					that.ChildListIndex = that.ChildsList.length
					if (that.ChildsList.length == 0) {
						that.addChildList()
					}
					that.$forceUpdate()
				} else if (that.popupName == '子表') {
					that.contents.splice(that.contentIndex, 1)
					if (that.contents.length == 0) {
						that.addtable()
					}
					that.$forceUpdate()
				} else if (that.popupcontent == '确定审核吗？') {
					that.submit('审核')
				}

			},

			toexamine() {
				var that = this
				that.popupName = ''
				that.popuptitle = '审核'
				that.popupcontent = '确定审核吗？'

				that.popup_logout = true


			},
			addChildList() {
				var that = this
				if (that.ChildListIndex == 5) {
					that.popupName = ''
					that.popuptitle = '报错'
					that.popupcontent = '最多5位质管员'
					that.popup_logout = true
				} else {
					var obj = {
						XJMan: '',
						XJNGNum: '',
						XJSituation: ''
					}
					that.ChildsList.push(obj)
					that.ChildListIndex = that.ChildsList.length
				}
				that.$forceUpdate()
			},
			trash(index) {
				var that = this;
				that.contentIndex = index
				that.popuptitle = '通知'
				that.popupName = '子表'
				that.popupcontent = `确定删除第${index+1}列吗？`
				that.popup_logout = true

			},
			addinput() {
				this.$forceUpdate()
			},
			addtable() {
				var that = this
				var obj = {
					CkPatrolDailyDeID: 0,
					time: '',
					Result: '',
					PicPath: '',
					DeadLine: getFormatDateTime(new Date()),
					Supervisor: '',
					Improvements: '',
					ResponseMan: '',
					Require: ['整改', '考核'],
					Situation: '',
					FWorkShopName: '17号车间',
					FWorkShopID: '1011',
					DImgs: [],
					QCName: that.$store.state.UserInfo.EmplName,
					FRemarks: '',
				}
				that.contents.push(obj)
				this.$forceUpdate()
			},

			getValue(e) {
				var that = this;
				console.log(e);
				if (e != '返回') {
					if (e.type == '日报责任人') {
						that.contents[that.comentIndex].ResponseMan = e.UserName
					} else if (e.type == '日报监督人') {
						that.contents[that.comentIndex].Supervisor = e.UserName
					} else if (e.type == '日报车间') {
						that.contents[that.comentIndex].FWorkShopID = e.FWorkshopID
						that.contents[that.comentIndex].FWorkShopName = e.FWorkshopName
					} else if (e.type == '质管员') {
						that.ChildsList[that.comentIndex].XJMan = e.UserName
					}

					this.$forceUpdate()
				}

			},

			deleteScreen(index) {
				var that = this;
				that.contentIndex = index

				that.popuptitle = '通知'
				that.popupName = '主表'
				that.popupcontent = `确定删除第${index+1}列吗？`
				that.popup_logout = true



			},
			openBaseScreen(str, index) {
				var that = this;
				console.log(str);
				that.comentIndex = index
				var obj;
				if (str == '日报责任人') {
					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '日报监督人') {
					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '日报车间') {

					obj = {
						cmd: 'Droplist_Workshop',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'FWorkshopName', //查询结果显示的字段
						},
						param: {

						}
					}

				} else if (str == '质管员') {
					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							pageSizeStr: 'PageSize', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '质量',
							PageIndex: 1,
							PageSize: 30
						}
					}

				}


				console.log(obj);
				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},
			deletePic(event, index) {
				console.log(event, index);
				this.contents[index].DImgs.splice(event.index, 1);
				this.$forceUpdate()
			},
			async afterRead(event, index) {
				console.log(event, index);

				let lists = [].concat(event.file)
				let fileListLen = this.contents[index].DImgs.length;
				console.log(fileListLen);
				lists.map((item) => {
					this.contents[index].DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.contents[index].DImgs[fileListLen]
					this.contents[index].DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.Request.IPAgreement() + this.Request.serverIP() + result
					}))
					fileListLen++
					console.log(this.contents[index].DImgs);
				}
				this.$forceUpdate()
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Request.IPAgreement() + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '巡查日报',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置 
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							// console.log(data);
							resolve(data.data)
						}
					});
				})
			},

			submit(str) {
				var that = this;
				var show = true
				var msg
				that.contents.forEach(item => {
					if (item.FWorkShopID == '' || item.FWorkShopID == null) {
						msg = '请选择巡检车间'
						show = false
					}
				})
				if (show) {
					const prefix = that.Request.IPAgreement() + that.Request.serverIP();
					that.contents.forEach(item => item.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					}))
					var list = JSON.parse(JSON.stringify(that.contents))

					list.forEach(item => {
						if (item.QCName == '' || item.QCName == null) {
							item.QCName = '@'
						}
						if (item.Situation == '' || item.Situation == null) {
							item.Situation = '@'
						}
						if (item.FWorkShopName == '' || item.FWorkShopName == null) {
							item.FWorkShopName = '@'
						}
						if (item.ResponseMan == '' || item.ResponseMan == null) {
							item.ResponseMan = '@'
						}
						if (item.Require == '' || item.Require == null) {
							item.Require = '@'
						}
						if (item.Improvements == '' || item.Improvements == null) {
							item.Improvements = '@'
						}
						if (item.Supervisor == '' || item.Supervisor == null) {
							item.Supervisor = '@'
						}
						if (item.FRemarks == '' || item.FRemarks == null) {
							item.FRemarks = '@'
						}
						if (item.DeadLine == '' || item.DeadLine == null) {
							item.DeadLine = '@'
						}
						if (item.DImgs.length == 0) {
							item.DImgs.push({
								url: '@'
							})
						}
					})

					console.log(that.ChildsList);
					var obj = {
						CkPatrolDailyID: that.ChildList.CkPatrolDailyID,
						CkPatrolDailyDeID: list.map(item => item.CkPatrolDailyDeID).join('~'),
						FWorkShopID: list.map(item => item.FWorkShopID).join('~'),
						QCName: list.map(item => item.QCName).join('~'),
						Situation: list.map(item => item.Situation).join('~'),
						FWorkShopName: list.map(item => item.FWorkShopName).join('~'),
						CheckTime: that.CheckTime,
						ResponseMan: list.map(item => item.ResponseMan).join('~'),
						Require: list.map(item => item.Require.join(',')).join('~'),
						PicPath: list.map(item => item.DImgs.map(itm => itm.url).join(',')).join('~'),
						Supervisor: list.map(item => item.Supervisor).join('~'),
						Improvements: list.map(item => item.Improvements).join('~'),
						FRemarks: list.map(item => item.FRemarks).join('~'),
						DeadLine: list.map(item => item.DeadLine).join('~'),
						XJSituation1: that.ChildsList[0] ? that.ChildsList[0].XJSituation : '',
						XJSituation2: that.ChildsList[1] ? that.ChildsList[1].XJSituation : '',
						XJSituation3: that.ChildsList[2] ? that.ChildsList[2].XJSituation : '',
						XJSituation4: that.ChildsList[3] ? that.ChildsList[3].XJSituation : '',
						XJSituation5: that.ChildsList[4] ? that.ChildsList[4].XJSituation : '',
						XJNGNum1: that.ChildsList[0] ? that.ChildsList[0].XJNGNum : '',
						XJNGNum2: that.ChildsList[1] ? that.ChildsList[1].XJNGNum : '',
						XJNGNum3: that.ChildsList[2] ? that.ChildsList[2].XJNGNum : '',
						XJNGNum4: that.ChildsList[3] ? that.ChildsList[3].XJNGNum : '',
						XJNGNum5: that.ChildsList[4] ? that.ChildsList[4].XJNGNum : '',
						XJMan1: that.ChildsList[0] ? that.ChildsList[0].XJMan : '',
						XJMan2: that.ChildsList[1] ? that.ChildsList[1].XJMan : '',
						XJMan3: that.ChildsList[2] ? that.ChildsList[2].XJMan : '',
						XJMan4: that.ChildsList[3] ? that.ChildsList[3].XJMan : '',
						XJMan5: that.ChildsList[4] ? that.ChildsList[4].XJMan : '',
						FRemarksZ: that.ChildList.FRemarksZ,

					}
					console.log(obj);
					that.loadingPage = true
					that.Request.request('savePatrolDailyDetail', obj, function(ret) {
						console.log(JSON.stringify(ret));
						if (ret.status == 200) {
							that.loadingPage = false
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							if (str == '审核') {
								var obj1 = {
									Type: 'XJRB',
									ID: ret.data.ds[0].CkPatrolDailyID
								}
								that.Request.request('ApproveXJConfirm', obj1, (res) => {
									if (res.status == 200) {
										that.$refs.uToast.show({
											title: '审核',
											type: 'success',
											message: '审核成功'
										})
										setTimeout(() => {
											that.queryList(ret.data.ds[0].CkPatrolDailyID)
										}, 1000)
									}

								})
							} else {
								setTimeout(() => {
									that.queryList(ret.data.ds[0].CkPatrolDailyID)
								}, 1000)
							}
						}
					})

				} else {
					that.loadingPage = false
					that.popuptitle = '报错'
					that.popupName = ''
					that.popupcontent = msg
					that.popup_logout = true
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getPatrolDailyDetail', {
						CkPatrolDailyID: id
					}, (ret) => {
						console.log(ret.data);
						var num = 0

						ret.data.ds.forEach((item, index) => {
							var stringArray = item.PicPath.split(',')
							if (stringArray[0] != '' && stringArray.length > 0) {
								item.DImgs = stringArray.map(item => ({
									url: that.Request.IPAgreement() + that.Request.serverIP() +
										item
										.trim()
								}));
							} else {
								item.DImgs = []
							}
							item.Require = item.Require.split(',')
							item.DeadLine = item.DeadLine ? item.DeadLine.split('T')[0] : ''
							that.CheckTime = item.CheckTime ? item.CheckTime.replace('T',
								' ') : ''
						})

						var list = ret.data.ds[0]
						console.log(ret.data.ds[0]);

						const result = [];
						for (let i = 1; i <= 5; i++) {
							const xKey = `XJMan${i}`;
							const jKey = `XJSituation${i}`;
							const NKey = `XJNGNum${i}`;
							const xValue = list[xKey];
							const jValue = list[jKey];
							const nValue = list[NKey];

							if (xValue != '' || jValue != '' || nValue != '') {

								result.push({
									XJMan: xValue,
									XJSituation: jValue,
									XJNGNum: nValue
								});
							}
						}
						that.ChildsList = result

						that.ChildListIndex = that.ChildsList.length
						that.contents = ret.data.ds
						that.ChildList = ret.data.ds[0]
						if (that.ChildList.Approve == true) {
							that.buttonShow = false
						} else {
							that.buttonShow = true
						}
						that.$forceUpdate()
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},


			pickerConfirm(e) {
				let that = this;
				console.log(e);
				var time = getFormatDateTime(e.value)
				console.log(time);
				that.contents[that.TimeIndex].DeadLine = time
				that.show = false
			},
			addTime(index) {
				this.TimeIndex = index
				this.show = true
			},
			planIDClick(item, index) {
				let that = this;
				that.hoveredIndex = index; // 设置当前hover的tr索引  
			},
			changeLevel(data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');

			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	::v-deep.uni-data-checklist .checklist-group {
		display: block !important;
	}


	.u-upload__button {
		width: 50px !important;
		height: 50px !important;
		margin: 0 !important;
	}

	.u-upload__wrap__preview {
		width: 50px !important;
		height: 50px !important;
		margin: 0 !important;
	}

	.u-row_view {
		background-color: #fff;
		padding: 5px 0px 0 10px;

		.u-row_view_right {
			text-align: center;
			font-size: 18px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 5% 0 15%;

			button {
				margin: 0;
				background: #51d0d0;
				color: #fff;
			}
		}

		.u-row_view_left {
			font-size: 18px;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.table table {
		tr td {
			input {
				width: 100%;
				background-color: #e7e7e7 !important;
			}
		}

	}

	.loading-page {
		background-color: rgba(0, 0, 0, 0.5) !important;
	}

	.th_view {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.u_icon {
		float: right;
	}

	.trashView {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;

		.u-icon {
			display: inline-block;
		}
	}
</style>